package com.shitou.shitoumember.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shitou.shitoumember.entity.MemberEntity;
import com.shitou.shitoumember.service.MemberService;
import com.shitou.shitoumember.service.impl.MemberServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import com.shitou.shitoucommons.utils.RespBean;

/**
 * class detail:
 *
 * @author 石头人
 */
@SuppressWarnings("all")
@Slf4j
@Component
public class InterceptorUtils {

    @Autowired
    private MemberService memberService;

    /**
     * 功能描述: 将信息渲染到响应体中，并返回
     * @param response
     * @param sessionError RespBeanEnum枚举类
     * @throws IOException
     */
    public void render(HttpServletResponse response, RespBean errorInfo) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.write(new ObjectMapper().writeValueAsString(errorInfo));
        printWriter.flush();
        printWriter.close();
    }

    /**
     * 通过Cookie获取token，然后获得当前登录用户
     * @param request
     * @param response
     * @return
     */
    public MemberEntity getUserByCookie(HttpServletRequest request, HttpServletResponse response, String ticket) {
        // 获得本地所有的cookie
        Cookie[] cookies = request.getCookies();
        if ( cookies != null ) {
            // 迭代所有的cookies
            for (Cookie cookie : cookies) {
                // 判断cookie里面是否存放了用户的令牌
                // 如果存放了，那么取出
                if (cookie.getName().equals(ticket) && !StringUtils.isEmpty(cookie.getValue())) {
                    String token = cookie.getValue();
                    // 获取用户信息，判断是否有，没有则
                    MemberEntity member = memberService.getMemberByToken(token, request, response);

                    return member;
                }
            }
        }
        return null;
    }

    /**
     * 通过Session获取token，然后获得当前登录用户
     * @param request
     * @param response
     * @return
     */
    public MemberEntity getUserBySession(HttpServletRequest request, HttpServletResponse response, String ticket) {
        // 获得Session
        HttpSession session = request.getSession();
        // 获取token
        String token = (String)session.getAttribute(ticket);
        if ( !StringUtils.isEmpty(token) ){
            // 根据用户的令牌返回具体的用户
            MemberEntity member = memberService.getMemberByToken(token, request, response);
            return member;
        }
        return null;
    }
}
